<template>
	<view class="user-container">
		<!-- 用户信息头部 -->
		<view class="user-header">
			<view class="user-info-section">
				<view class="avatar-container" @click="handleAvatarClick">
					<image v-if="displayUserInfo.avatar" :src="$tools.buildUrl(displayUserInfo.avatar)"
						mode="aspectFill" class="avatar-image"></image>
					<view class="avatar-placeholder" v-if="!displayUserInfo.avatar">
						<text class="avatar-text">{{ displayUserInfo.name.charAt(0) || '茶' }}</text>
					</view>
				</view>
				<view class="user-details">
					<text class="user-name">{{ displayUserInfo.name }}</text>
					<text class="user-level" v-if="isLogin">普通会员</text>
					<text class="user-level" v-else @click="goToLogin">点击登录</text>
				</view>
				<view class="header-actions">
					<view v-if="isLogin" class="scan-btn" @click="scanGetPoints">
						<u-icon name="scan" size="24" color="#ffffff"></u-icon>
					</view>
					<view v-if="isLogin" class="settings-btn" @click="editProfile">
						<text class="iconfont">⚙️</text>
					</view>
				</view>
			</view>

			<!-- 用户数据统计 -->
			<view class="user-stats">
				<view class="stat-item" @click="viewBalance">
					<text class="stat-number">{{ displayUserInfo.balance || '0.00' }}</text>
					<text class="stat-label">余额</text>
				</view>
				<view class="stat-item" @click="toPointsMall">
					<text class="stat-number">{{ displayUserInfo.points || '0' }}</text>
					<text class="stat-label">积分</text>
				</view>
				<view class="stat-item" @click="toPointsCards">
					<text class="stat-number">{{ displayUserInfo.pointsCards || '0' }}</text>
					<text class="stat-label">积分卡</text>
				</view>
				<view class="stat-item" @click="handleMemberClick({path: '/pages/user/coupon'})">
					<text class="stat-number">{{ userInfo.couponCount || '0' }}</text>
					<text class="stat-label">优惠券</text>
				</view>
			</view>
		</view>

		<!-- 我的订单 -->
		<view class="section-card">
			<view class="section-header" @click="toOrderList(0)">
				<text class="section-title">我的订单</text>
				<view class="section-more">
					<text class="more-text">查看全部</text>
					<text class="arrow">></text>
				</view>
			</view>
			<view class="order-grid">
				<view class="order-item" v-for="(item, index) in orderStatusList.slice(1)" :key="index"
					@click="toOrderList(item.status)">
					<view class="order-icon">
						<text class="order-emoji">{{ item.emoji }}</text>
						<view v-if="item.badge>0" class="order-badge">
							<text class="badge-text">{{ item.badge }}</text>
						</view>
					</view>
					<text class="order-text">{{ item.name }}</text>
				</view>
			</view>
		</view>

		<!-- 常用工具 -->
		<view class="section-card">
			<view class="section-header">
				<text class="section-title">常用工具</text>
			</view>
			<view class="tools-grid">
				<view class="tool-item" v-for="(item, index) in toolsList" :key="index" @click="handleToolClick(item)">
					<view class="tool-icon">
						<text class="tool-emoji">{{ item.emoji }}</text>
					</view>
					<text class="tool-text">{{ item.name }}</text>
				</view>
			</view>
		</view>

		<!-- 服务中心 -->
		<view class="section-card">
			<!-- <view class="section-header">
				<text class="section-title">服务中心</text>
			</view> -->
			<view class="service-list">
				<view class="service-item" v-for="(item, index) in serviceList" :key="index">
					<!-- 在线客服使用微信小程序客服功能 -->
					<button v-if="item.isContact" class="contact-service-btn" open-type="contact"
						@contact="handleContact">
						<view class="service-left">
							<text class="service-emoji">{{ item.emoji }}</text>
							<text class="service-name">{{ item.name }}</text>
						</view>
						<text class="service-arrow">&gt;</text>
					</button>

					<!-- 其他服务项 -->
					<view v-else class="service-content" @click="handleServiceClick(item)">
						<view class="service-left">
							<text class="service-emoji">{{ item.emoji }}</text>
							<text class="service-name">{{ item.name }}</text>
						</view>
						<text class="service-arrow">&gt;</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				// 用户扩展信息（非登录相关）
				userExtInfo: {
					balance: '0.00',
					points: '0',
					pointsCards: '0',
					couponCount: '0'
				},
				// 订单状态列表
				orderStatusList: [{
						name: '全部订单',
						emoji: '📋',
						status: 0 // 'all'
					},
					{
						name: '待付款',
						emoji: '💰',
						status: 1, // 'pending',
						badge: '0'
					},
					{
						name: '待发货',
						emoji: '📦',
						status: 2, // 'shipped',
						badge: '0'
					},
					{
						name: '待收货',
						emoji: '🚚',
						status: 3, // 'delivering',
						badge: '0'
					},
					{
						name: '售后',
						emoji: '🔄',
						status: 6, // 'service',
						badge: '0'
					}
				],
				// 常用工具列表
				toolsList: [{
						name: '每日签到',
						emoji: '📅',
						action: 'signIn'
					},
					{
						name: '收货地址',
						emoji: '📍',
						path: '/pages/user/address'
					},
					{
						name: '优惠券',
						emoji: '🎫',
						path: '/pages/user/coupon'
					},
					{
						name: '分销中心',
						emoji: '💼',
						path: '/fenxiao-package/distribution/index'
					},
					{
						name: '经销商中心',
						emoji: '🏪',
						path: '/dealer-package/index'
					},
					{
						name: '余额明细',
						emoji: '💳',
						path: '/pages/user/balance-detail'
					},
					{
						name: '积分商城',
						emoji: '⭐',
						path: '/points-package/product/points'
					},
					{
						name: '积分规则',
						emoji: '📋',
						path: '/points-package/rules/points-rules'
					},
					{
						name: '售后服务',
						emoji: '🛠️',
						path: '/pages/after-sale/list'
					},
					{
						name: '收藏夹',
						emoji: '❤️',
						path: '/pages/user/favorites'
					},
					// {
					// 	name: '浏览记录',
					// 	emoji: '👁️',
					// 	path: '/pages/user/history'
					// },
				],
				// 服务列表
				serviceList: [{
						name: '在线客服',
						emoji: '💬',
						isContact: true // 标识为微信客服
					},
					// {
					// 	name: '意见反馈',
					// 	emoji: '📝',
					// 	path: '/pages/service/feedback'
					// },
					// {
					// 	name: '帮助中心',
					// 	emoji: '❓',
					// 	path: '/pages/service/help'
					// },
					{
						name: '供链合作',
						emoji: '🤝',
						path: '/pages/cooperation/supply'
					},
					{
						name: '招商加盟',
						emoji: '💼',
						path: '/pages/investment/join'
					},
					{
						name: '线下门店',
						emoji: '🏪',
						path: '/pages/store/list'
					},
					{
						name: '关于我们',
						emoji: 'ℹ️',
						path: '/pages/service/contact'
					},
					{
						name: '修改密码',
						emoji: '🔑',
						action: 'changePassword'
					},
					{
						name: '退出登录',
						emoji: '🚪',
						action: 'logout'
					}
				]
			}
		},

		computed: {
			...mapGetters(['isLogin', 'userInfo']),
			// 合并用户信息
			displayUserInfo() {
				if (this.isLogin && this.userInfo.nickname) {
					return {
						name: this.userInfo.nickname,
						avatar: this.userInfo.avatar_url,
						...this.userExtInfo
					}
				} else {
					return {
						name: '未登录',
						avatar: '',
						...this.userExtInfo
					}
				}
			}
		},

		onShow() {
			this.loadUserExtInfo();
			this.loadOrderStatusList();
		},

		methods: {
			loadUserExtInfo() {
				this.$api.user.GetUserExtInfo().then(res => {
					this.userExtInfo = {
						balance: res.data.balance.toFixed(2),
						points: res.data.points,
						pointsCards: res.data.pointsCards,
						couponCount: res.data.couponCount
					}
				})
			},
			loadAccountInfo() {
				this.$api.user.GetUserExtInfo3().then(res => {
					this.userExtInfo = {
						balance: res.data.balance.toFixed(2)
					}
				})
			},
			loadPointInfo() {
				this.$api.user.GetUserExtInfo2().then(res => {
					this.userExtInfo = {
						points: res.data.points,
						pointsCards: res.data.pointsCards
					}
				})
			},
			loadCouponInfo() {
				this.$api.user.GetUserExtInfo3().then(res => {
					this.userExtInfo = {
						couponCount: res.data.couponCount
					}
				})
			},
			loadOrderStatusList() {
				this.$api.order.GetOrderStatusList().then(res => {
					if (res.data.pendingCount) {
						this.orderStatusList[1].badge = res.data.pendingCount
					}
					if (res.data.shippedCount) {
						this.orderStatusList[2].badge = res.data.shippedCount
					}
					if (res.data.deliveringCount) {
						this.orderStatusList[3].badge = res.data.deliveringCount
					}
					if (res.data.serviceCount) {
						this.orderStatusList[4].badge = res.data.serviceCount
					}
				})
			},
			// 跳转到订单列表
			toOrderList(status = 0) {
				if (status === 6) {
					uni.navigateTo({
						url: '/pages/after-sale/list'
					})
				} else {
					let url = '/pages/order/list'
					if (status && status !== 0) {
						url += `?status=${status}`
					}
					uni.navigateTo({
						url: url
					})
				}
			},
			// 处理会员权益点击
			handleMemberClick(item) {
				if (item.path) {
					uni.navigateTo({
						url: item.path
					})
				} else {
					uni.showToast({
						title: '功能开发中',
						icon: 'none',
						duration: 2000
					})
				}
			},
			// 处理工具点击
			handleToolClick(item) {
				if (item.action) {
					// 处理特殊操作
					switch (item.action) {
						case 'signIn':
							this.signInToday()
							break
					}
				} else if (item.path) {
					uni.navigateTo({
						url: item.path
					})
				} else {
					uni.showToast({
						title: '功能开发中',
						icon: 'none',
						duration: 2000
					})
				}
			},
			// 处理服务点击
			handleServiceClick(item) {
				if (item.action) {
					// 处理特殊操作
					switch (item.action) {
						case 'changePassword':
							this.changePassword()
							break
						case 'logout':
							this.logout()
							break
					}
				} else if (item.path) {
					uni.navigateTo({
						url: item.path
					})
				} else {
					uni.showToast({
						title: '功能开发中',
						icon: 'none',
						duration: 2000
					})
				}
			},
			// 处理头像点击
			handleAvatarClick() {
				if (this.isLogin) {
					this.editProfile()
				} else {
					this.goToLogin()
				}
			},
			// 跳转到登录页面
			goToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			// 编辑个人资料
			editProfile() {
				uni.navigateTo({
					url: '/pages/user/profile'
				})
			},
			// 查看余额明细
			viewBalance() {
				uni.navigateTo({
					url: '/pages/user/balance-detail'
				})
			},
			// 跳转到积分商城
			toPointsMall() {
				uni.navigateTo({
					url: '/points-package/product/points'
				})
			},
			// 跳转到积分卡页面
			toPointsCards() {
				uni.navigateTo({
					url: '/points-package/record/points-cards'
				})
			},
			// 计算积分卡总数（弃用）
			getTotalCards() {
				const pointsCards = {
					S: 2,
					A: 5,
					B: 8,
					C: 12,
					D: 15
				}
				const cards = this.userInfo.pointsCards || {}
				return Object.values(cards).reduce((total, count) => total + count, 0)
			},

			// 修改密码
			changePassword() {
				uni.navigateTo({
					url: '/pages/user/change-password'
				})
			},
			// 退出登录
			logout() {
				if (!this.isLogin) {
					uni.showToast({
						title: '您还未登录',
						icon: 'none',
						duration: 2000
					})
					return
				}

				uni.showModal({
					title: '确认退出',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 使用vuex退出登录
							this.$store.dispatch('logout')

							uni.showToast({
								title: '退出成功',
								icon: 'success',
								duration: 2000
							})

							// 跳转到登录页面
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}, 1500)
						}
					}
				})
			},

			// 处理微信客服
			handleContact(e) {
				// console.log('客服消息：', e.detail)
				// 可以在这里处理客服会话的相关逻辑

				// 如果需要，可以显示提示
				if (e.detail.errMsg === 'contact:ok') {
					// 用户进入客服会话
					// console.log('用户进入客服会话')
				}
			},

			// 今日签到
			signInToday() {
				// 任务类型：1 - 注册积分 2 - 推荐积分 3 - 分享积分 4 - 消费积分 5 - 签到积分
				this.$api.point.CompletePointsTask({
					task_type: 5,
					task_desc: '今日已签到'
				}).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'success',
						duration: 2000
					})
					this.loadUserExtInfo();
				})
			},

			// 扫一扫获取积分
			scanGetPoints() {
				uni.authorize({
					scope: 'scope.camera', // 申请相机权限
					success: () => {
						// 授权成功后调用扫码
						uni.scanCode({
							onlyFromCamera: false,
							scanType: ['qrCode', 'barCode'],
							success: (res) => {
								// console.log('扫码结果:', res);
								if (res.result && res.result != '') {
									// 任务类型：1-注册积分 2-推荐积分 3-分享积分 4-消费积分 5-签到积分
									const barcode = this.$secret.decryptAES(res.result)
									if (barcode && barcode !== '') {
										this.$api.point.CompletePointsTask({
											task_type: 4,
											task_desc: '扫码领积分',
											scan_code: barcode
										}).then(res => {
											this.loadPointInfo();
											uni.showToast({
												title: res.msg,
												icon: 'success',
												duration: 2000
											})
										})
									}
								}
							},
							fail: (err) => {
								// console.error('扫码失败:', err);
								uni.showToast({
									title: '扫码失败，请重试',
									icon: 'none',
									duration: 2000
								})
							}
						});
					},
					fail: () => {
						uni.showToast({
							title: "请授权相机权限",
							icon: 'none',
							duration: 2000
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.user-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding-bottom: 160rpx;
	}

	/* 用户头部区域 */
	.user-header {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		padding: 60rpx 30rpx 40rpx;
		color: white;
	}

	.user-info-section {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.avatar-container {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		overflow: hidden;
		background-color: rgba(255, 255, 255, 0.2);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 30rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.3);
	}

	.avatar-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.avatar-placeholder {
		width: 100%;
		height: 100%;
		background-color: rgba(255, 255, 255, 0.1);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.avatar-text {
		font-size: 48rpx;
		color: white;
		font-weight: bold;
	}

	.user-details {
		flex: 1;
	}

	.user-name {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
		display: block;
	}

	.user-level {
		font-size: 24rpx;
		opacity: 0.8;
		background-color: rgba(255, 255, 255, 0.2);
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		display: inline-block;
	}

	.header-actions {
		display: flex;
		gap: 20rpx;
	}

	.scan-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 30rpx;
	}

	.settings-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 30rpx;
	}

	/* 用户数据统计 */
	.user-stats {
		display: flex;
		justify-content: space-around;
		background-color: rgba(255, 255, 255, 0.1);
		border-radius: 20rpx;
		padding: 30rpx 0;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex: 1;
	}

	.stat-number {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
		display: block;
	}

	.stat-label {
		font-size: 24rpx;
		opacity: 0.8;
	}

	/* 通用卡片样式 */
	.section-card {
		background-color: white;
		margin: 20rpx 30rpx;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 30rpx 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.section-more {
		display: flex;
		align-items: center;
	}

	.more-text {
		font-size: 26rpx;
		color: #999;
		margin-right: 8rpx;
	}

	.arrow {
		font-size: 24rpx;
		color: #999;
	}

	/* 订单网格样式 */
	.order-grid {
		display: flex;
		padding: 0 30rpx 30rpx;
		justify-content: space-between;
	}

	.order-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.order-icon {
		width: 80rpx;
		height: 80rpx;
		margin-bottom: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f8f9fa;
		border-radius: 50%;
		position: relative;
	}

	.order-emoji {
		font-size: 36rpx;
	}

	.order-badge {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		background-color: #ff4757;
		color: white;
		font-size: 20rpx;
		padding: 2rpx 8rpx;
		border-radius: 20rpx;
		min-width: 24rpx;
		text-align: center;
	}

	.badge-text {
		font-size: 20rpx;
	}

	.order-text {
		font-size: 24rpx;
		color: #666;
		text-align: center;
	}

	/* 工具网格样式 */
	.tools-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
		padding: 0 30rpx 30rpx;
	}

	.tool-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx 20rpx;
		background-color: #f8f9fa;
		border-radius: 16rpx;
		transition: all 0.3s ease;
	}

	.tool-item:active {
		background-color: #e9ecef;
		transform: scale(0.95);
	}

	.tool-icon {
		width: 60rpx;
		height: 60rpx;
		margin-bottom: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tool-emoji {
		font-size: 32rpx;
	}

	.tool-text {
		font-size: 24rpx;
		color: #333;
		text-align: center;
	}

	/* 服务列表样式 */
	.service-list {
		padding: 0 30rpx 20rpx;
	}

	.service-item {
		border-bottom: 1rpx solid #f0f0f0;
	}

	.service-item:last-child {
		border-bottom: none;
	}

	.service-left {
		display: flex;
		align-items: center;
	}

	.service-emoji {
		font-size: 32rpx;
		margin-right: 20rpx;
	}

	.service-name {
		font-size: 28rpx;
		color: #333;
	}

	.service-arrow {
		font-size: 24rpx;
		color: #999;
	}

	/* 微信客服按钮 */
	.contact-service-btn {
		width: 100%;
		background: transparent;
		border: none;
		padding: 24rpx 0;
		margin: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
		color: #333;
		text-align: left;
		line-height: 1.4;
		min-height: 80rpx;
		box-sizing: border-box;
	}

	.contact-service-btn::after {
		border: none;
	}

	.service-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 0;
		min-height: 80rpx;
		box-sizing: border-box;
	}
</style>